package towerz.game.level;

import javax.microedition.lcdui.Graphics;
import towerz.game.Tileset;

import towerz.system.Utilities;
import towerz.system.xml.XmlNode;
import towerz.system.xml.XmlReaderWriter;

public class Map {
	protected Map() {
		//initialize
		m_Width		= 1;
		m_Height	= 1;
		m_Tiles		= null;
		m_Tileset	= null;
	}

	public Map(String mapStr, String tileset) {
		//Default
		this();

        String tilesetImg = null, buildable = null;
        XmlNode xmlNode = XmlReaderWriter.getInstance().readFromXmlFile(Utilities.TILESET_FOLDER + "/" + tileset);

		//For each children
        for(int i=0; i<xmlNode.getChildren().size(); ++i){
			//Read tag
            String Tag 		= ((XmlNode)xmlNode.getChildren().elementAt(i)).getNodeName();
			String Value 	= ((XmlNode)((XmlNode)xmlNode.getChildren().elementAt(i)).getChildren().elementAt(0)).getNodeValue();

			//Save based on tag
            if(Tag.equals("image"))				tilesetImg = Value;
			else if(Tag.equals("buildable"))	buildable = Value;
        }


		//Create tileset
		m_Tileset = new Tileset(Utilities.TILESET_FOLDER + "/" + tilesetImg, buildable);

		//Get height
		if (System.getProperty("line.separator") != null)	m_Height = Utilities.split(mapStr, System.getProperty("line.separator")).length;
		else												m_Height = Utilities.split(mapStr, 10).length;

		//Get tiles
		String[] splitted	= Utilities.split(mapStr, ";");
		m_Width				= splitted.length / m_Height;
		m_Tiles				= new int[m_Width][m_Height];
		
		//Fill the m_Tiles
		for(int i=0; i<m_Height; ++i){
			for(int j=0; j<m_Width; ++j){
				m_Tiles[j][i] = Integer.parseInt(splitted[(i*m_Width) + j]);
			}
		}
	}

    public boolean isTileBuildable(int x, int y){
        return (m_Tileset.isTileBuildable(m_Tiles[x][y]));
    }

	public int getWidth() {
		return m_Width;
	}

	public int getHeight() {
		return m_Height;
	}

	public void draw(Graphics g, int startX, int startY, int endX, int endY, int offsetX, int offsetY) {
		//Draw tiles
		for (int y = endY - 1; y >= startY; y--) {
			for (int x = startX; x < endX; x++) {
				//Draw
				g.drawImage(
					m_Tileset.getTile(m_Tiles[x][y]),
					((x - startX) * Utilities.TILE_WIDTH) + offsetX,
					((y - startY) * Utilities.TILE_HEIGHT) + offsetY,
					Graphics.LEFT | Graphics.TOP );
			}
		}
	}
	
	//Data
	protected int 		m_Width;
	protected int 		m_Height;
	protected int[][] 	m_Tiles;
	protected Tileset	m_Tileset;
}

